import React, { useState, useEffect } from 'react';
import History, { HistoryItem, HistoryType } from './History';
import dayjs from 'dayjs';
import './Calculator.css';

interface CalculatorParams {
    productId: string;
    profitValue: number;
    profitType: 'fixed' | 'cost' | 'price';
    cost: number;
    coupon: number;
    discount: number;
    preTaxPrice: number;
    weight: number;
    withdrawalFeeRate: number;
    platformCommissionRate: number;
    sfpFeeRate: number;
    talentCommissionRate: number;
    transactionFeeRate: number;
    vatRate: number;
    bonusCashbackRate: number;
    logisticsCostPer10g: number;
    exchangeRate: number;
    buyerShippingFee: number;
}

interface CalculationResult {
    productId: string;
    profitValue: number;
    profitType: 'fixed' | 'cost' | 'price';
    cost: number;
    coupon: number;
    discount: number;
    preTaxPrice: number;
    weight: number;
    withdrawalFeeRate: number;
    platformCommissionRate: number;
    sfpFeeRate: number;
    talentCommissionRate: number;
    transactionFeeRate: number;
    vatRate: number;
    bonusCashbackRate: number;
    logisticsCostPer10g: number;
    exchangeRate: number;
    buyerShippingFee: number;
    finalPrice: number;
    timestamp: string;
    crossBorderDelivery: number;
    local: number;
    pay: number;
    platformCommission: number;
    sfpFee: number;
    talentCommission: number;
    transactionFee: number;
    vat: number;
    bonusCashbackFee: number;
    actualProfit: number;
}

type CalculationMode = 'preTax' | 'discount' | 'history';

const Calculator: React.FC = () => {
    const [mode, setMode] = useState<CalculationMode>('preTax');
    const [preTaxParams, setPreTaxParams] = useState<CalculatorParams>({
        productId: '',
        profitValue: 15,
        profitType: 'price',
        cost: 0,
        coupon: 2,
        discount: 3,
        preTaxPrice: 0,
        weight: 0,
        withdrawalFeeRate: 0.01,
        platformCommissionRate: 0.054,
        sfpFeeRate: 0,
        talentCommissionRate: 0,
        transactionFeeRate: 0.0378,
        vatRate: 0.1,
        bonusCashbackRate: 0.0435,
        logisticsCostPer10g: 0.15,
        exchangeRate: 1.6412,
        buyerShippingFee: 10
    });

    const [discountParams, setDiscountParams] = useState<CalculatorParams>({
        productId: '',
        profitValue: 15,
        profitType: 'price',
        cost: 0,
        coupon: 2,
        discount: 3,
        preTaxPrice: 0,
        weight: 0,
        withdrawalFeeRate: 0.01,
        platformCommissionRate: 0.054,
        sfpFeeRate: 0,
        talentCommissionRate: 0,
        transactionFeeRate: 0.0378,
        vatRate: 0.1,
        bonusCashbackRate: 0.0435,
        logisticsCostPer10g: 0.15,
        exchangeRate: 1.6412,
        buyerShippingFee: 10
    });

    const [preTaxResult, setPreTaxResult] = useState<CalculationResult | null>(null);
    const [discountResult, setDiscountResult] = useState<CalculationResult | null>(null);
    const [history, setHistory] = useState<HistoryItem[]>([]);
    const [searchId, setSearchId] = useState<string>('');
    const [historyType, setHistoryType] = useState<HistoryType>('all');
    const [historyError, setHistoryError] = useState<string>('');

    const [error, setError] = useState<string>('');

    // Update profit value label based on profit type
    useEffect(() => {
        const profitValueLabel = document.querySelector('label[for="profitValue"]');
        if (profitValueLabel) {
            const currentParams = mode === 'preTax' ? preTaxParams : discountParams;
            if (currentParams.profitType === 'fixed') {
                profitValueLabel.textContent = '利润值(CNY)';
            } else {
                profitValueLabel.textContent = '利润值(%)';
            }
        }
    }, [mode, preTaxParams.profitType, discountParams.profitType]);

    // 添加获取历史记录的函数
    const fetchLatestHistory = async (productId: string) => {
        try {
            const response = await fetch(`http://localhost:3000/api/history?product_id=${productId}&type=all`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            if (!response.ok) {
                throw new Error('获取历史记录失败');
            }
            const { data } = await response.json();
            if (data && data.length > 0) {
                // 获取最新的记录
                const latestRecord = data[0];
                // 更新折扣参数
                setDiscountParams(prev => ({
                    ...prev,
                    profitValue: latestRecord.profit_value,
                    profitType: latestRecord.profit_type,
                    cost: latestRecord.cost,
                    coupon: latestRecord.coupon,
                    weight: latestRecord.weight,
                    withdrawalFeeRate: latestRecord.withdrawal_fee_rate,
                    platformCommissionRate: latestRecord.platform_commission_rate,
                    sfpFeeRate: latestRecord.sfp_fee_rate,
                    talentCommissionRate: latestRecord.talent_commission_rate,
                    transactionFeeRate: latestRecord.transaction_fee_rate,
                    vatRate: latestRecord.vat_rate,
                    bonusCashbackRate: latestRecord.bonus_cashback_rate,
                    logisticsCostPer10g: latestRecord.logistics_cost_per_10g,
                    exchangeRate: latestRecord.exchange_rate,
                    buyerShippingFee: latestRecord.buyer_shipping_fee,
                    preTaxPrice: latestRecord.y,
                }));
            }
        } catch (err) {
            console.error('获取历史记录失败:', err);
            setError(err instanceof Error ? err.message : '获取历史记录时发生错误');
        }
    };

    // 修改 handleInputChange 函数
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        const updateParams = (prev: CalculatorParams) => ({
            ...prev,
            [name]: name === 'productId' || name === 'profitType' ? value : parseFloat(value) || 0
        });

        if (mode === 'preTax') {
            setPreTaxParams(updateParams);
        } else {
            setDiscountParams(updateParams);
        }
    };

    const calculate = async () => {
        try {
            const currentParams = mode === 'preTax' ? preTaxParams : discountParams;
            // Transform the parameters before sending
            const requestParams = {
                ...currentParams,
                off: mode === 'preTax' ? currentParams.discount / 10 : undefined,
                y: mode === 'discount' ? currentParams.preTaxPrice : undefined,
                // Remove mode and other unnecessary parameters
                mode: undefined,
                discount: undefined,
                preTaxPrice: undefined
            };

            const response = await fetch('http://localhost:3000/api/calculate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestParams),
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || '计算失败');
            }

            const { data } = await response.json();
            
            if (mode === 'preTax') {
                // 税前售价计算模式
                const newResult = {
                    ...preTaxParams,
                    finalPrice: data.y,
                    timestamp: new Date().toISOString(),
                    // 添加计算结果字段
                    crossBorderDelivery: data.crossBorderDelivery,
                    local: data.local,
                    pay: data.pay,
                    platformCommission: data.platformCommission,
                    sfpFee: data.sfpFee,
                    talentCommission: data.talentCommission,
                    transactionFee: data.transactionFee,
                    vat: data.vat,
                    bonusCashbackFee: data.bonusCashbackFee,
                    actualProfit: data.actualProfit
                };
                setPreTaxResult(newResult);
            } else {
                // 折扣率计算模式
                // 根据calc.html的逻辑，折扣率 = (1 - off) * 10
                const newDiscount = (1 - data.off) * 10;
                const newResult = {
                    ...discountParams,
                    finalPrice: (1 - data.off) * 100, // 折扣率百分比
                    discount: newDiscount, // 更新折扣值
                    timestamp: new Date().toISOString(),
                    // 添加计算结果字段
                    crossBorderDelivery: data.crossBorderDelivery,
                    local: data.local,
                    pay: data.pay,
                    platformCommission: data.platformCommission,
                    sfpFee: data.sfpFee,
                    talentCommission: data.talentCommission,
                    transactionFee: data.transactionFee,
                    vat: data.vat,
                    bonusCashbackFee: data.bonusCashbackFee,
                    actualProfit: data.actualProfit
                };
                setDiscountResult(newResult);
                // 更新折扣参数
                setDiscountParams(prev => ({
                    ...prev,
                    discount: newDiscount
                }));
            }
            setError('');
        } catch (err) {
            setError(err instanceof Error ? err.message : '计算过程中发生错误');
            if (mode === 'preTax') {
                setPreTaxResult(null);
            } else {
                setDiscountResult(null);
            }
        }
    };

    const saveResult = async () => {
        const currentParams = mode === 'preTax' ? preTaxParams : discountParams;
        if (!currentParams) return;

        try {
            const saveData = {
                product_id: currentParams.productId,
                profit_value: currentParams.profitValue,
                profit_type: currentParams.profitType,
                cost: currentParams.cost,
                coupon: currentParams.coupon,
                off: mode === 'preTax' ? 100 - currentParams.discount * 10 : discountResult?.discount as number * 10,
                y: mode === 'preTax' ? preTaxResult?.finalPrice : discountParams.preTaxPrice,
                weight: currentParams.weight,
                withdrawal_fee_rate: currentParams.withdrawalFeeRate,
                platform_commission_rate: currentParams.platformCommissionRate,
                sfp_fee_rate: currentParams.sfpFeeRate,
                talent_commission_rate: currentParams.talentCommissionRate,
                transaction_fee_rate: currentParams.transactionFeeRate,
                vat_rate: currentParams.vatRate,
                bonus_cashback_rate: currentParams.bonusCashbackRate,
                logistics_cost_per_10g: currentParams.logisticsCostPer10g,
                exchange_rate: currentParams.exchangeRate,
                buyer_shipping_fee: currentParams.buyerShippingFee,
                type: mode === 'preTax' ? 'pricing' : 'adjustment',
                created_at: dayjs().format('YYYY-MM-DD HH:mm')
            };

            const response = await fetch('http://localhost:3000/api/calculations', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(saveData),
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || '保存失败');
            }
        } catch (err) {
            setError(err instanceof Error ? err.message : '保存结果时发生错误');
        }
    };

    return (
        <div className="calculator">
            <div className="tabs">
                <button 
                    className={`tab ${mode === 'preTax' ? 'active' : ''}`}
                    onClick={() => setMode('preTax')}
                >
                    计算税前售价
                </button>
                <button 
                    className={`tab ${mode === 'discount' ? 'active' : ''}`}
                    onClick={() => setMode('discount')}
                >
                    计算折扣率
                </button>
                <button 
                    className={`tab ${mode === 'history' ? 'active' : ''}`}
                    onClick={() => setMode('history')}
                >
                    定价记录
                </button>
            </div>
            {
                mode === 'history' ? (
                    <div className="history-container">
                        <History 
                            onSearch={async() => {
                                if (!searchId) {
                                    setHistoryError('请输入产品ID');
                                    return;
                                }
                                try {
                                    const url = `http://localhost:3000/api/history?product_id=${searchId}&type=${historyType}`;
                                    
                                    const response = await fetch(url);
                                    if (!response.ok) {
                                        throw new Error('获取历史记录失败');
                                    }
                                    const data = await response.json();
                                    if (!Array.isArray(data.data)) {
                                        console.error('API返回的数据不是数组:', data);
                                        setHistory([]);
                                        return;
                                    }
                                    setHistory(data.data);
                                    setHistoryError('');
                                } catch (err) {
                                    console.error('获取历史记录时发生错误:', err);
                                    setHistoryError(err instanceof Error ? err.message : '获取历史记录时发生错误');
                                    setHistory([]);
                                }  
                            }} 
                            onHistoryTypeChange={setHistoryType}
                            onSearchChange={setSearchId}
                            dataSource={history}
                            searchId={searchId}
                            historyType={historyType} 
                            historyError={historyError}
                        />
                    </div>
                ) : (
                    <div className="form-container">
                        {mode === 'preTax' ? (
                            // 计算税前售价表单
                            <>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="productId">产品ID</label>
                                        <input
                                            type="text"
                                            id="productId"
                                            name="productId"
                                            value={preTaxParams.productId}
                                            onChange={handleInputChange}
                                            placeholder="请输入产品ID"
                                        />
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="profitValue">利润值(%)</label>
                                        <input
                                            type="number"
                                            id="profitValue"
                                            name="profitValue"
                                            value={preTaxParams.profitValue}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入利润值"
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label htmlFor="profitType">利润类型</label>
                                        <select
                                            id="profitType"
                                            name="profitType"
                                            value={preTaxParams.profitType}
                                            onChange={handleInputChange}
                                        >
                                            <option value="fixed">固定利润</option>
                                            <option value="cost">成本利润率</option>
                                            <option value="price">售价利润率</option>
                                        </select>
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="cost">成本（采购价 + 货代）</label>
                                        <input
                                            type="number"
                                            id="cost"
                                            name="cost"
                                            value={preTaxParams.cost}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入成本"
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label htmlFor="coupon">优惠券(外币)</label>
                                        <input
                                            type="number"
                                            id="coupon"
                                            name="coupon"
                                            value={preTaxParams.coupon}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入优惠券金额"
                                        />
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="weight">重量(g)</label>
                                        <input
                                            type="number"
                                            id="weight"
                                            name="weight"
                                            value={preTaxParams.weight}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入重量"
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label htmlFor="discount">折扣</label>
                                        <input
                                            type="number"
                                            id="discount"
                                            name="discount"
                                            value={preTaxParams.discount}
                                            onChange={handleInputChange}
                                            min="1"
                                            max="9"
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入折扣"
                                        />
                                    </div>
                                </div>
                            </>
                        ) : (
                            // 计算折扣率表单
                            <>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="productId">产品ID</label>
                                        <div className="input-with-button">
                                            <input
                                                type="text"
                                                id="productId"
                                                name="productId"
                                                value={discountParams.productId}
                                                onChange={handleInputChange}
                                                placeholder="请输入产品ID"
                                            />
                                            {mode === 'discount' && (
                                                <button 
                                                    className="query-button"
                                                    onClick={() => discountParams.productId && fetchLatestHistory(discountParams.productId)}
                                                    disabled={!discountParams.productId}
                                                >
                                                    查询参数
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="preTaxPrice">税前售价(CNY)</label>
                                        <input
                                            type="number"
                                            id="preTaxPrice"
                                            name="preTaxPrice"
                                            value={discountParams.preTaxPrice}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入税前售价"
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label htmlFor="profitValue">利润值(%)</label>
                                        <input
                                            type="number"
                                            id="profitValue"
                                            name="profitValue"
                                            value={discountParams.profitValue}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入利润值"
                                        />
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="profitType">利润类型</label>
                                        <select
                                            id="profitType"
                                            name="profitType"
                                            value={discountParams.profitType}
                                            onChange={handleInputChange}
                                        >
                                            <option value="fixed">固定利润</option>
                                            <option value="cost">成本利润率</option>
                                            <option value="price">售价利润率</option>
                                        </select>
                                    </div>
                                    <div className="form-group">
                                        <label htmlFor="cost">成本（采购价 + 货代）</label>
                                        <input
                                            type="number"
                                            id="cost"
                                            name="cost"
                                            value={discountParams.cost}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入成本"
                                        />
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group">
                                        <label htmlFor="coupon">优惠券(外币)</label>
                                        <input
                                            type="number"
                                            id="coupon"
                                            name="coupon"
                                            value={discountParams.coupon}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入优惠券金额"
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label htmlFor="weight">重量(g)</label>
                                        <input
                                            type="number"
                                            id="weight"
                                            name="weight"
                                            value={discountParams.weight}
                                            onChange={handleInputChange}
                                            onWheel={(e) => e.currentTarget.blur()}
                                            placeholder="请输入重量"
                                        />
                                    </div>
                                </div>
                            </>
                        )}

                        <div className="form-section">
                            <h3>高级参数</h3>
                            <div className="form-row">
                                <div className="form-group">
                                    <label htmlFor="withdrawalFeeRate">提现手续费率</label>
                                    <input
                                        type="number"
                                        id="withdrawalFeeRate"
                                        key={mode + '_withdrawalFeeRate'}
                                        name="withdrawalFeeRate"
                                        value={mode === 'preTax' ? preTaxParams.withdrawalFeeRate : discountParams.withdrawalFeeRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="platformCommissionRate">平台佣金比例</label>
                                    <input
                                        type="number"
                                        id="platformCommissionRate"
                                        key={mode + '_platformCommissionRate'}
                                        name="platformCommissionRate"
                                        value={mode === 'preTax' ? preTaxParams.platformCommissionRate : discountParams.platformCommissionRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="sfpFeeRate">SFP服务费率</label>
                                    <input
                                        type="number"
                                        id="sfpFeeRate"
                                        key={mode + '_sfpFeeRate'}
                                        name="sfpFeeRate"
                                        value={mode === 'preTax' ? preTaxParams.sfpFeeRate : discountParams.sfpFeeRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                            </div>
                            <div className="form-row">
                                <div className="form-group">
                                    <label htmlFor="talentCommissionRate">达人佣金比例</label>
                                    <input
                                        type="number"
                                        id="talentCommissionRate"
                                        key={mode + '_talentCommissionRate'}
                                        name="talentCommissionRate"
                                        value={mode === 'preTax' ? preTaxParams.talentCommissionRate : discountParams.talentCommissionRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="transactionFeeRate">交易手续费率</label>
                                    <input
                                        type="number"
                                        id="transactionFeeRate"
                                        key={mode + '_transactionFeeRate'}
                                        name="transactionFeeRate"
                                        value={mode === 'preTax' ? preTaxParams.transactionFeeRate : discountParams.transactionFeeRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="vatRate">增值税率</label>
                                    <input
                                        type="number"
                                        id="vatRate"
                                        key={mode + '_vatRate'}
                                        name="vatRate"
                                        value={mode === 'preTax' ? preTaxParams.vatRate : discountParams.vatRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                            </div>
                            <div className="form-row">
                                <div className="form-group">
                                    <label htmlFor="logisticsCostPer10g">跨境物流成本(每10g)</label>
                                    <input
                                        type="number"
                                        id="logisticsCostPer10g"
                                        key={mode + '_logisticsCostPer10g'}
                                        name="logisticsCostPer10g"
                                        value={mode === 'preTax' ? preTaxParams.logisticsCostPer10g : discountParams.logisticsCostPer10g}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="exchangeRate">汇率(外币→本币)</label>
                                    <input
                                        type="number"
                                        id="exchangeRate"
                                        key={mode + '_exchangeRate'}
                                        name="exchangeRate"
                                        value={mode === 'preTax' ? preTaxParams.exchangeRate : discountParams.exchangeRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="buyerShippingFee">买家支付运费(外币)</label>
                                    <input
                                        type="number"
                                        id="buyerShippingFee"
                                        key={mode + '_buyerShippingFee'}
                                        name="buyerShippingFee"
                                        value={mode === 'preTax' ? preTaxParams.buyerShippingFee : discountParams.buyerShippingFee}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                            </div>
                            <div className="form-row">
                                <div className="form-group">
                                    <label htmlFor="bonusCashbackRate">奖金返现服务费率</label>
                                    <input
                                        type="number"
                                        id="bonusCashbackRate"
                                        key={mode + '_bonusCashbackRate'}
                                        name="bonusCashbackRate"
                                        value={mode === 'preTax' ? preTaxParams.bonusCashbackRate : discountParams.bonusCashbackRate}
                                        onChange={handleInputChange}
                                        onWheel={(e) => e.currentTarget.blur()}
                                    />
                                </div>
                                <div className="form-group" />
                                <div className="form-group" />
                            </div>
                        </div>

                        <div className="button-group">
                            <button onClick={calculate}>
                                {mode === 'preTax' ? '计算税前售价' : '计算折扣率'}
                            </button>
                            <button onClick={saveResult} disabled={!((mode === 'preTax' && preTaxResult) || (mode === 'discount' && discountResult))}>保存</button>
                        </div>
                    </div>
                )
            }

            {error && <div className="error">{error}</div>}

            {preTaxResult && (
                <div className="result" style={{ display: mode === 'preTax' ? 'block' : 'none' }}>
                    <h3>计算结果:</h3>
                    <div className="result-content">
                        <div className="result-item">
                            <span className="label">税前售价:</span>
                            <span className="value">{preTaxResult.finalPrice.toFixed(2)} (CNY) {((preTaxResult.finalPrice / preTaxResult.exchangeRate).toFixed(2))} (外币)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">本地展示价:</span>
                            <span className="value">{preTaxResult.local.toFixed(2)} (CNY) {((preTaxResult.local / preTaxResult.exchangeRate).toFixed(2))} (外币)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">预估买家实付:</span>
                            <span className="value">{(preTaxResult.pay / preTaxResult.exchangeRate).toFixed(2)} (外币)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">跨境物流成本:</span>
                            <span className="value">{preTaxResult.crossBorderDelivery.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">平台佣金:</span>
                            <span className="value">{preTaxResult.platformCommission.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">SFP服务费:</span>
                            <span className="value">{preTaxResult.sfpFee.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">达人佣金:</span>
                            <span className="value">{preTaxResult.talentCommission.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">交易手续费:</span>
                            <span className="value">{preTaxResult.transactionFee.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">增值税:</span>
                            <span className="value">{preTaxResult.vat.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">奖金返现服务费:</span>
                            <span className="value">{preTaxResult.bonusCashbackFee.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">预估利润:</span>
                            <span className="value">{preTaxResult.actualProfit.toFixed(2)} (CNY)</span>
                        </div>
                    </div>
                </div>
            )}

            {discountResult && (
                <div className="result" style={{ display: mode === 'discount' ? 'block' : 'none' }}>
                    <h3>计算结果:</h3>
                    <div className="result-content">
                        <div className="result-item">
                            <span className="label">折扣率:</span>
                            <span className="value">{(discountResult.finalPrice).toFixed(2)}%</span>
                        </div>
                        <div className="result-item">
                            <span className="label">本地展示价:</span>
                            <span className="value">{discountResult.local.toFixed(2)} (CNY) {((discountResult.local / discountResult.exchangeRate).toFixed(2))} (外币)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">跨境物流成本:</span>
                            <span className="value">{discountResult.crossBorderDelivery.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">预估买家实付:</span>
                            <span className="value">{(discountResult.pay / discountResult.exchangeRate).toFixed(2)} (外币)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">平台佣金:</span>
                            <span className="value">{discountResult.platformCommission.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">SFP服务费:</span>
                            <span className="value">{discountResult.sfpFee.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">达人佣金:</span>
                            <span className="value">{discountResult.talentCommission.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">交易手续费:</span>
                            <span className="value">{discountResult.transactionFee.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">增值税:</span>
                            <span className="value">{discountResult.vat.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">奖金返现服务费:</span>
                            <span className="value">{discountResult.bonusCashbackFee.toFixed(2)} (CNY)</span>
                        </div>
                        <div className="result-item">
                            <span className="label">预估利润:</span>
                            <span className="value">{discountResult.actualProfit.toFixed(2)} (CNY)</span>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Calculator;